<template>
  <BubbleList :list="messageList" max-height="68vh" ref="bubbleListRef">
    <template #avatar="{ item }">
      <div class="avatar-wrapper">
        <img :src="item.avatarUrl" alt="avatar" />
      </div>
    </template>
    <template #header="{ item }">
      <div class="header-wrapper">
        <div class="header-name">
          {{ item.nickName }}
        </div>
      </div>
    </template>
    <template #content="{ item }">
      <div class="content-wrapper">
        <div
          class="content-text"
          :class="item.placement === 'end' ? 'right' : 'left'"
        >
          {{ item.content }}
        </div>
      </div>
    </template>
    <template #footer="{ item }">
      <div class="footer-wrapper">
        <div class="footer-time">
          {{ item.createTime }}
        </div>
      </div>
    </template>
  </BubbleList>
</template>

<script setup lang="ts">
import { onBeforeUnmount, ref } from "vue";
import { getRoomChatMessageList, sendRoomChatMessage } from "../../../api/chat";
import { useStudyRoomStore, useUserStore } from "@/stores";
const userStroe = useUserStore();
const studyRoomStore = useStudyRoomStore();
// 参考 ChatContent.vue 的结构，增加 role/placement 字段
const messageList = ref([]);
const bubbleListRef = ref();
import { Client } from "@stomp/stompjs";
import { formatDate } from "@/utils/common";
// 供父组件调用，追加新消息
function appendMessage(content: string) {
  sendRoomChatMessageHandler(content);
  // 滚动到底部
  bubbleListRef.value?.scrollToBottom?.();
}
const sendRoomChatMessageHandler = async (message: string) => {
  try {
    const request = {
      roomId: studyRoomStore.currentRoom.roomId,
      message: message,
      fromId: userStroe.currentUser.userId,
      nickName: userStroe.currentUser.nickname,
      avatarUrl: userStroe.currentUser.avatarUrl,
      createTime: formatDate(new Date()),
    };
    console.log("request===========》:", request);
    const response = await sendRoomChatMessage(request);
    console.log("发送聊天室消息成功:", response);
  } catch (error) {
    console.error("发送聊天室消息失败:", error);
  }
};
const generateRandomMessage = (params) => {
  var data = {
    key: params.chatId,
    placement: params.fromId === userStroe.currentUser.userId ? "end" : "start",
    nickName: params.nickName,
    avatarUrl: params.avatarUrl,
    content: params.message,
    createTime: params.createTime,
    noStyle: true,
  };
  messageList.value.push(data);
};
const getRoomChatMessageListHandler = async (roomId: string) => {
  try {
    const response = await getRoomChatMessageList(roomId);
    if (response && response.data) {
      console.log("获取聊天室消息成功:", response.data);
      response.data.forEach((item: any) => {
        generateRandomMessage(item);
      });
    }
  } catch (error) {
    console.error("获取聊天室消息失败:", error);
  }
};
getRoomChatMessageListHandler(studyRoomStore.currentRoom.roomId);
let MQClient = new Client(); // 消息队列客户端
MQClient.configure({
  brokerURL: import.meta.env.VITE_MQ_WEBSOCKET_URL, // 替换为你的消息队列地址
  connectHeaders: {
    login: import.meta.env.VITE_MQ_USERNAME,
    passcode: import.meta.env.VITE_MQ_PASSWORD,
    host: import.meta.env.VITE_MQ_HOST,
  },
  debug: (str) => {
    console.log(str);
  },
  onConnect: () => {
    console.log("MQ连接成功==================");
    MQClient.subscribe(
      `/exchange/room_exchange/chat.${studyRoomStore.currentRoom.roomId}`,
      (message) => {
        console.log("接收到消息:", message);
        if (message.body) {
          const params = JSON.parse(message.body);
          console.log("接收到消息:", params);
          generateRandomMessage(params);
        }
      }
    );
  },
  onStompError: (frame) => {
    console.error("MQ连接错误:", frame.headers["message"]);
  },
});
//结束，销毁
onBeforeUnmount(() => {
  if (MQClient && MQClient.connected) {
    MQClient.deactivate();
    console.log("MQ连接已断开");
  }
});
MQClient.activate();
defineExpose({ appendMessage });
</script>

<style scoped lang="less">
.avatar-wrapper {
  width: 40px;
  height: 40px;
  img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
}

.header-wrapper {
  .header-name {
    font-size: 14px;
    color: #979797;
  }
}

.content-wrapper {
  .content-text {
    font-size: 14px;
    color: #333;
    padding: 12px;
    background: linear-gradient(to right, #fdfcfb 0%, #ffd1ab 100%);
    border-radius: 15px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    &.right {
      background: linear-gradient(to left, #fdfcfb 0%, #aee1f9 100%);
      text-align: right;
    }
    &.left {
      background: linear-gradient(to right, #fdfcfb 0%, #ffd1ab 100%);
      text-align: left;
    }
  }
}

.footer-wrapper {
  display: flex;
  align-items: center;
  gap: 10px;
  .footer-time {
    font-size: 12px;
    margin-top: 3px;
  }
}
</style>
